package com.core.springSecurity.service;

import com.common.utils.Constants;
import com.common.redis.RedisCache;
import com.common.utils.StringUtils;
import com.common.utils.uuid.IdUtils;
import com.core.springSecurity.model.TempUserKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zql
 * @Description: 用户临时密钥生成服务
 * @Data: 8:37 2021/7/23
 */
@Slf4j
@Service
public class TempUserKeyService {

    @Value("${TempUserKeyService.expireTime:5}")
    private int expireTime;

    @Resource
    private RedisCache redisCache;

    /**
     * @Author: zql
     * @Description: 创建临时密钥
     * @param sysUserId 用户唯一id
     * @Data: 9:45 2021/7/23
     */
    public void create(Long sysUserId,String key){
        TempUserKey tempUserKey =new TempUserKey();
        tempUserKey.setSysUserId(sysUserId);
        tempUserKey.setLoginTime(System.currentTimeMillis());
        tempUserKey.setExpireTime(tempUserKey.getLoginTime() + expireTime * Constants.MINUTE_MILLIS);
        redisCache.setCacheObject(key, tempUserKey, expireTime, TimeUnit.MINUTES);
    }

    public String createPasswordKey(Long sysUserId){
        String passwordKey = IdUtils.fastUUID();
        String key= getPasswordKey(passwordKey);
        create(sysUserId,key);
        return passwordKey;
    }

    /**
     * @Author: zql
     * @Description: 获得用户表中id
     * @param passwordKey 唯一id
     * @Data: 9:44 2021/7/23
     */
    public Long getValueByPasswordKey(String passwordKey){
        String key= getPasswordKey(passwordKey);
        TempUserKey tempUserKey = redisCache.getCacheObject(key);
        if(StringUtils.isNull(tempUserKey)){
            return 0L;
        }
        redisCache.deleteObject(key);
        return tempUserKey.getSysUserId();
    }

    /**
     * @Author: zql
     * @Description: 加上临时密钥key的前缀
     * @param uuid 唯一id
     * @Data: 9:44 2021/7/23
     */
    private String getPasswordKey(String uuid) {
        return Constants.USER_KEY + uuid;
    }
}
